package com.mls.guardian.appst.chain.excutor;

import com.mls.guardian.appst.chain.TaskExecutor;
import com.mls.guardian.appst.chain.TaskInvoker;
import com.mls.guardian.appst.chain.TaskResult;
import com.mls.guardian.appst.shell.ShellScriptExecutorFuture;
import com.mls.guardian.common.FileUtil;
import com.mls.guardian.dataobj.ModuleMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * Created by pengrenfang on 15/11/6.
 */
public class StopProcessExcutor implements TaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(StopProcessExcutor.class);

    @Override
    public TaskResult exec(TaskInvoker invoker) {

        TaskResult result = null;
        try {
            log.info("----开始stop process----");
            result = this.killJar(invoker);
            if (result.isSuc() == true) {
                result = this.killTomcat(invoker);
            }
        } catch (Exception e) {
            log.info("----stop process[{}]----", false);
            result = new TaskResult();
            result.setSuc(false);
            result.setError(e.getMessage());

            e.printStackTrace();
        } finally {
            log.info("----结束stop process[{}]----", result.isSuc());
        }

        if (result.isSuc() == true) {
            return invoker.invoke();
        }

        return result;
    }

    private TaskResult killTomcat(TaskInvoker invoker) throws Exception {
        TaskResult result = null;
        for (ModuleMessage item : invoker.getModuleList()) {
            if (item.getModuleName().toLowerCase().equals("tomcat") || invoker.getProject().getWebModuleList().contains(item.getModuleName())) {
                for (String itemTomcatHome : invoker.getProject().getTomcatHomeList()) {
                    String bashFilePath = System.getProperty("user.home") + File.separator + "guardianConfig" + File.separator + "guardian_" + System.currentTimeMillis() + ".sh";
                    try {
                        log.info("----stop tomcat process[{}]----", itemTomcatHome);
                        if (false == itemTomcatHome.substring(itemTomcatHome.length() - 1, itemTomcatHome.length()).equals(File.separator)) {
                            itemTomcatHome = itemTomcatHome + File.separator;
                        }
                        FileUtil.append(bashFilePath, "pid=$(ps -ef|grep tomcat |grep spring.profiles.active |grep " + itemTomcatHome + " |awk '{print $2}')");
                        FileUtil.append(bashFilePath, "echo killing $pid");
                        FileUtil.append(bashFilePath, "OLD_IFS=\"$IFS\"");
                        FileUtil.append(bashFilePath, "IFS=\" \"");
                        FileUtil.append(bashFilePath, "arr=($pid)");
                        FileUtil.append(bashFilePath, "IFS=\"$OLD_IFS\"");
                        FileUtil.append(bashFilePath, "for s in ${arr[@]}");
                        FileUtil.append(bashFilePath, "do");
                        FileUtil.append(bashFilePath, "echo killed $s");
                        FileUtil.append(bashFilePath, "kill -9 $s");
                        FileUtil.append(bashFilePath, "done");
                        FileUtil.append(bashFilePath, "echo kill pid finished");

                        result = new ShellScriptExecutorFuture("sh " + bashFilePath).execute();
                        //有一个报错,结束任务
                        if (result.isSuc() == false) {
                            break;
                        }
                    } catch (Exception e) {
                        result = new TaskResult();
                        result.setSuc(false);
                        result.setError(e.getMessage());

                        e.printStackTrace();
                    } finally {
                        try {
                            Files.deleteIfExists(Paths.get(bashFilePath));
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }//end-for
                break;
            }
        }
        if (result == null) {
            result = new TaskResult();
            result.setSuc(true);
        }

        return result;
    }

    private TaskResult killJar(TaskInvoker invoker) throws Exception {
        TaskResult result = null;
        for (ModuleMessage item : invoker.getModuleList()) {
            String bashFilePath = System.getProperty("user.home") + File.separator + "guardianConfig" + File.separator + "guardian_" + System.currentTimeMillis() + ".sh";
            try {
                if (item.getModuleName().toLowerCase().equals("tomcat") || invoker.getProject().getWebModuleList().contains(item.getModuleName())) {
                    //
                } else {
                    log.info("----stop jar process[{}]----", item.getModuleName());
                    FileUtil.append(bashFilePath, "pid=$(ps -ef|grep java |grep " + item.getModuleName() + ".jar |awk '{print $2}')");
                }
                FileUtil.append(bashFilePath, "echo killing $pid");
                FileUtil.append(bashFilePath, "OLD_IFS=\"$IFS\"");
                FileUtil.append(bashFilePath, "IFS=\" \"");
                FileUtil.append(bashFilePath, "arr=($pid)");
                FileUtil.append(bashFilePath, "IFS=\"$OLD_IFS\"");
                FileUtil.append(bashFilePath, "for s in ${arr[@]}");
                FileUtil.append(bashFilePath, "do");
                FileUtil.append(bashFilePath, "echo killed $s");
                FileUtil.append(bashFilePath, "kill -9 $s");
                FileUtil.append(bashFilePath, "done");
                FileUtil.append(bashFilePath, "echo kill pid finished");

                result = new ShellScriptExecutorFuture("sh " + bashFilePath).execute();

                //有一个报错,结束任务
                if (result.isSuc() == false) {
                    break;
                }
            } catch (Exception e) {
                result = new TaskResult();
                result.setSuc(false);
                result.setError(e.getMessage());

                e.printStackTrace();
            } finally {
                try {
                    Files.deleteIfExists(Paths.get(bashFilePath));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        if (result == null) {
            result = new TaskResult();
            result.setSuc(true);
        }

        return result;
    }
}
